package com.we823.project.repository.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.we823.project.model.UserModel;
import com.we823.project.repository.dao.UserRepository;
import com.we823.project.repository.service.sys.RoleService;
import com.we823.project.repository.service.we.RoleResourcePermissionService;
import com.we823.utils.web.StringUtil;

@Service("userService")
public class UserService extends AbstractBaseService<UserModel> {

	@Autowired
	private RoleResourcePermissionService roleResourcePermissionService;
	@Autowired
	private RoleService roleService;
	
	private UserRepository userRepository;
	
	@Autowired
	public UserService(UserRepository userRepository) {
		super(userRepository);
		this.userRepository = userRepository;
	}

	public UserModel findByUsername(String username) {
		return userRepository.findByUsername(username);
	}

	public Map<Integer, UserModel> map() {
		List<UserModel> userModels = findAll();
		Map<Integer, UserModel> map = new HashMap<Integer, UserModel>();
		if(userModels!=null) {
			for (UserModel userModel : userModels) {
				map.put(userModel.getId(), userModel);
			}
		}
		return map;
	}
	
	public Set<String> findStringPermission(UserModel userModel){
		Set<String> permissionSet = new HashSet<>();
		if(userModel!=null) {
			String roleids = userModel.getRoleIds();
			if(!StringUtils.isBlank(roleids)) {
				List<Integer> roleidList = new ArrayList<>();
				StringUtil.toIntegerList(roleids, roleidList);
				if(roleidList!=null && roleidList.size()>0) {
					permissionSet = roleResourcePermissionService.findStringPermissionByRoleidIn(roleidList);
				}
			}
		}
		
		return permissionSet;
	}

	public Set<String> findStringRole(UserModel userModel){
		Set<String> result = new HashSet<>();
		if(userModel!=null) {
			List<Integer> roleidList = new ArrayList<>();
			StringUtil.toIntegerList(userModel.getRoleIds(), roleidList);
			
			result = roleService.findRolesByRoleidIn(roleidList);
		}
		return result;
	}
	public RoleResourcePermissionService getRoleResourcePermissionService() {
		return roleResourcePermissionService;
	}

	public void setRoleResourcePermissionService(
			RoleResourcePermissionService roleResourcePermissionService) {
		this.roleResourcePermissionService = roleResourcePermissionService;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public List<UserModel> findByIdIn(List<Integer> userIdList) {
		return userRepository.findByIdIn(userIdList);
	}

	
}
